package ae.pcfc.etks.cld.to.web.constraints;



import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.web.multipart.MultipartFile;

import ae.pcfc.etks.cld.to.web.util.StringUtils;



/**
 * 
 * @author arosa
 *
 */
public class ImageFileValidator implements ConstraintValidator<ImageFile, MultipartFile> {

	Set<String> imgExt = new HashSet<String>(Arrays.asList(new String[]{"jpg","jpeg","png","gif","bmp","jp","pdf"}));
	
	public void initialize(ImageFile constraintAnnotation) {
		
	}

	public boolean isValid(MultipartFile value,
			ConstraintValidatorContext context) {
		String ext = null;
		if(value!=null){
			String fileName = value.getOriginalFilename();
			
			if(!fileName.isEmpty()){
				ext = StringUtils.getFileExtension(fileName);
				ext = ext.toLowerCase();
			}
		}
		boolean result = value==null || value.isEmpty() || (!value.getOriginalFilename().isEmpty() && (imgExt.contains(ext) || (ext.equals("pdf"))));
		return result;
	}

}
